package com.epoint.pjq.core.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * 
 * @author lilin
 * @date 2016年9月14日 上午9:39:36
 * @annotation MQTT 客户端
 */
public class SMP_MQTT_EpointClient extends MqttClient {

	private SMP_MQTT_EpointClient(String serverURI, String clientId,MqttClientPersistence persistence) throws MqttException {
		super(serverURI, clientId, persistence);
	}

	private static SMP_MQTT_EpointClient instance = null;

	public static SMP_MQTT_EpointClient getInstance()
	{
		if(instance==null){
			synchronized (SMP_MQTT_EpointClient.class) {
				try {
					String topic 	= SMP_MQTT_Service.topic;
					String HOSTURI 	= SMP_MQTT_Service.hosturi;
					
					MemoryPersistence persistence = new MemoryPersistence();
					instance = new SMP_MQTT_EpointClient(HOSTURI, topic, persistence);
				} catch (MqttException e) {
					e.printStackTrace();
				}
			}
		}
		return instance;
	}

	/**
	 * 初始化创建MQTT客户端
	 * @param KEEPALIVETIME
	 * @param TOPIC
	 */
	public void initClient(int KEEPALIVETIME,String TOPIC)
	{
		try{
			SMP_MQTT_Bizlogic.sendLogBroadcast("正在连接..." +"ClientID:"+instance.getClientId()+" HostUri:"+instance.getServerURI()+" KeepAliveTime:"+KEEPALIVETIME);
			
			MqttConnectOptions connectionOption = new MqttConnectOptions();
			connectionOption.setKeepAliveInterval(KEEPALIVETIME);
			connectionOption.setConnectionTimeout(10);
			connectionOption.setCleanSession(false);
			instance.setCallback(new SMP_MQTT_CallBack());
			instance.connect();
			instance.subscribe(new String[]{TOPIC}, new int[]{1});
			SMP_MQTT_Bizlogic.sendLogBroadcast("连接成功...");
		}catch(Exception e)
		{
			e.printStackTrace();
			SMP_MQTT_Bizlogic.sendLogBroadcast("连接失败...");
			SMP_MQTT_Bizlogic.sendLogBroadcast(e.getMessage());

			if(SMP_MQTT_Service.isStarted){
				SMP_MQTT_Bizlogic.sendLogBroadcast("<initClient>正在重新连接...");

				try {
					Thread.sleep(3000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				new SMP_MQTT_ConnectionThread().start();
			}
		}
	}

	/**
	 * 销毁客户端
	 */
	public void destory()
	{
		try {

			if(instance.isConnected()){
				SMP_MQTT_Bizlogic.sendLogBroadcast("MqttClient准备断开连接...");
				instance.disconnect();
				SMP_MQTT_Bizlogic.sendLogBroadcast("MqttClient准备关闭...");
				instance.close();
			}

			SMP_MQTT_Bizlogic.sendLogBroadcast("MqttClient设置为空...");
			instance = null;
			SMP_MQTT_Bizlogic.sendLogBroadcast("MqttClient销毁完成...");

		} catch (MqttException e) {
			e.printStackTrace();
			SMP_MQTT_Bizlogic.sendLogBroadcast("MqttClient销毁失败...");
		}
	}
}
